/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Interface;

import entidades.*;
import Controladores.*;
import Controladores.exceptions.NonexistentEntityException;
import Controladores.exceptions.PreexistingEntityException;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.filechooser.FileNameExtensionFilter;

/**
 *
 * @author Gatoper
 */
public class JPUPet extends javax.swing.JPanel {

    private Pet pet;

    /**
     * Creates new form JPUPet
     */
    public JPUPet() {
        initComponents();
        this.setSize(new Dimension(300, 400));

    }

    public JPUPet(Pet p) {
        this.pet = p;
        initComponents();
        this.setSize(new Dimension(500, 500));
        TAge.setText(p.getAge());
        TName.setText(p.getName());
        TSpecies.setText(p.getSpecies());
        TWeight.setText(p.getWeight());
        Tpicture.setText("<in db>");
        for (int i = 0; i < CBOwner.getModel().getSize(); i++) {
            if ((String) CBOwner.getModel().getElementAt(i) == p.getOwner().getName()) {
                CBOwner.setSelectedIndex(i);
                i = CBOwner.getModel().getSize();
            }
        }
        ImageIcon fot = new ImageIcon(p.getPicture());
        Icon icono = new ImageIcon(fot.getImage().getScaledInstance(97, 85, Image.SCALE_DEFAULT));
        Limg.setIcon(icono);
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("HPVAS");
        PetJpaController petJpaC = new PetJpaController(emf);
        this.Tapoi.setModel(petJpaC.findVacines(p.getName()));
        this.TVac.setModel(petJpaC.findAppoitmets(p.getName()));
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        BUpdate = new javax.swing.JButton();
        LSpecies = new javax.swing.JLabel();
        TWeight = new javax.swing.JTextField();
        TSpecies = new javax.swing.JTextField();
        Tpicture = new javax.swing.JTextField();
        LAge = new javax.swing.JLabel();
        TAge = new javax.swing.JTextField();
        LWeight = new javax.swing.JLabel();
        TName = new javax.swing.JTextField();
        LName = new javax.swing.JLabel();
        Lpicture = new javax.swing.JLabel();
        LOwner = new javax.swing.JLabel();
        CBOwner = new javax.swing.JComboBox();
        Bfile = new javax.swing.JButton();
        Limg = new javax.swing.JLabel();
        BDelete = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        TVac = new javax.swing.JTable();
        jScrollPane2 = new javax.swing.JScrollPane();
        Tapoi = new javax.swing.JTable();

        setMaximumSize(new java.awt.Dimension(300, 300));
        setPreferredSize(new java.awt.Dimension(260, 300));

        BUpdate.setText("Update");
        BUpdate.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BUpdateActionPerformed(evt);
            }
        });

        LSpecies.setText("Species :");

        Snumero(TWeight);

        Sletras(TSpecies);

        Tpicture.setEnabled(false);

        LAge.setText("Age :");

        Snumero(TAge);

        LWeight.setText("Weight :");

        Sletras(TName);
        TName.setEnabled(false);
        TName.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                TNameActionPerformed(evt);
            }
        });

        LName.setText("Name :");

        Lpicture.setText("Picture :");

        LOwner.setText("Owner :");

        EntityManagerFactory emf;
        EntityManager em;
        Map<String, String> properties=new HashMap<>();
        properties.put("javax.persistence.jdbc:user", "root");
        properties.put("javax.persistence.jdbc:password", "");
        emf=Persistence.createEntityManagerFactory("HPVAS",properties);
        em=emf.createEntityManager();
        Owner owner=new Owner();
        OwnerJpaController ojc=new OwnerJpaController(emf);
        List l=ojc.findOwnerEntities();
        String [] aux=new String[l.size()];
        for(int i=0;i<l.size();i++)
        aux[i]=((Owner)l.get(i)).getName();
        CBOwner.setModel(new javax.swing.DefaultComboBoxModel(aux));

        Bfile.setText("Attach");
        Bfile.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BfileActionPerformed(evt);
            }
        });

        BDelete.setText("Delete");
        BDelete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BDeleteActionPerformed(evt);
            }
        });

        TVac.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane1.setViewportView(TVac);

        Tapoi.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane2.setViewportView(Tapoi);

        TName.addFocusListener(new FocusAdapter() {
            public void focusGained(FocusEvent evt) {
                TIdFocusGained(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(LOwner)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(CBOwner, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(BUpdate)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(BDelete))
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                        .addGroup(layout.createSequentialGroup()
                                            .addComponent(LName)
                                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                            .addComponent(TName))
                                        .addGroup(layout.createSequentialGroup()
                                            .addComponent(LSpecies)
                                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                            .addComponent(TSpecies, javax.swing.GroupLayout.DEFAULT_SIZE, 187, Short.MAX_VALUE))
                                        .addGroup(layout.createSequentialGroup()
                                            .addComponent(LAge)
                                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                            .addComponent(TAge))
                                        .addGroup(layout.createSequentialGroup()
                                            .addComponent(LWeight)
                                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                            .addComponent(TWeight)))
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(Lpicture)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                            .addComponent(Tpicture)
                                            .addComponent(Limg, javax.swing.GroupLayout.DEFAULT_SIZE, 97, Short.MAX_VALUE))
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addComponent(Bfile, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE)))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 195, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 195, javax.swing.GroupLayout.PREFERRED_SIZE))))
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(LName)
                            .addComponent(TName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(LSpecies)
                            .addComponent(TSpecies, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(LAge)
                            .addComponent(TAge, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(LWeight)
                            .addComponent(TWeight, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(Lpicture)
                            .addComponent(Tpicture, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(Bfile))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(Limg, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(LOwner)
                    .addComponent(CBOwner, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(BUpdate)
                    .addComponent(BDelete))
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    private void TNameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_TNameActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_TNameActionPerformed

    private void BUpdateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BUpdateActionPerformed
        // TODO add your handling code here:
        EntityManagerFactory emf;
        EntityManager em;
        Map<String, String> properties = new HashMap<>();
        emf = Persistence.createEntityManagerFactory("HPVAS");
        em = emf.createEntityManager();

        PetJpaController petJpaC = new PetJpaController(emf);
        OwnerJpaController ojc = new OwnerJpaController(emf);
        String ownid = (String) this.CBOwner.getSelectedItem();
        Pet pet2;
        pet2 = new Pet(this.TName.getText(), this.TSpecies.getText(), this.TAge.getText(), this.TWeight.getText(), pet.getPicture(), ojc.findOwner(ownid));
        //file.getName()
        try {
            if(!this.Tpicture.getText().equals("<in db>")){
                File file = new File(this.Tpicture.getText());
                FileInputStream fis = new FileInputStream(file);
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                byte[] buf = new byte[1024];

                for (int readNum; (readNum = fis.read(buf)) != -1;) {
                    bos.write(buf, 0, readNum);
                    System.out.println("read " + readNum + " bytes,");
                }
                pet2.setPicture(bos.toByteArray());
            }
            petJpaC.edit(pet2);
            JOptionPane.showMessageDialog(this, "Perfecto.");
        } catch (IOException ex) {
            JOptionPane.showMessageDialog(this, "Archivo no encotrado");
        } catch (PreexistingEntityException ex) {
            JOptionPane.showMessageDialog(this, "La entidad que trata de editar ya no existe");
            Logger.getLogger(JPIPet.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "Error en ejecucion de su peticion");
            Logger.getLogger(JPIPet.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_BUpdateActionPerformed
    private void TIdFocusGained(FocusEvent evt) {
        this.TAge.setEnabled(false);
        this.TSpecies.setEnabled(false);
        this.TWeight.setEnabled(false);
        this.Tpicture.setEnabled(false);
        this.Bfile.setEnabled(false);
        this.BUpdate.setEnabled(false);
        this.CBOwner.setEnabled(false);
    }
    private void BfileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BfileActionPerformed
        // TODO add your handling code here:
        FileNameExtensionFilter filter = new FileNameExtensionFilter("JPEG file", "jpg", "jpeg");
        JFileChooser chooser = new JFileChooser();
        chooser.setAcceptAllFileFilterUsed(false);
        chooser.setDialogTitle("Choose Image..");
        chooser.setFileFilter(filter);
        chooser.addChoosableFileFilter(filter);
        chooser.showOpenDialog(null);
        File f = chooser.getSelectedFile();
        this.Tpicture.setText(f.getAbsolutePath());
        if (!this.Tpicture.getText().isEmpty()) {
            ImageIcon fot = new ImageIcon(this.Tpicture.getText());
            Icon icono = new ImageIcon(fot.getImage().getScaledInstance(Limg.getWidth(), Limg.getHeight(), Image.SCALE_DEFAULT));
            Limg.setIcon(icono);
            this.repaint();
        }
    }//GEN-LAST:event_BfileActionPerformed

    private void BDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BDeleteActionPerformed
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("HPVAS");
        EntityManager em = emf.createEntityManager();
        PetJpaController petJpaC = new PetJpaController(emf);
        try {
            petJpaC.destroy(this.TName.getText());
            JOptionPane.showMessageDialog(this, "Perfecto.");
        } catch (NonexistentEntityException ex) {
            JOptionPane.showMessageDialog(this, "Esta tratando de borrar una entidad que no existe");
            Logger.getLogger(JPUPet.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_BDeleteActionPerformed
    public void Snumero(JTextField a) {
        a.addKeyListener(new KeyAdapter() {
            public void keyTyped(KeyEvent e) {
                char c = e.getKeyChar();
                if (Character.isLetter(c)) {
                    e.consume();
                }
            }
        });
    }

    public void Sletras(JTextField a) {
        a.addKeyListener(new KeyAdapter() {
            public void keyTyped(KeyEvent e) {
                char c = e.getKeyChar();
                if (Character.isDigit(c)) {
                    e.consume();
                }
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton BDelete;
    private javax.swing.JButton BUpdate;
    private javax.swing.JButton Bfile;
    private javax.swing.JComboBox CBOwner;
    private javax.swing.JLabel LAge;
    private javax.swing.JLabel LName;
    private javax.swing.JLabel LOwner;
    private javax.swing.JLabel LSpecies;
    private javax.swing.JLabel LWeight;
    private javax.swing.JLabel Limg;
    private javax.swing.JLabel Lpicture;
    private javax.swing.JTextField TAge;
    private javax.swing.JTextField TName;
    private javax.swing.JTextField TSpecies;
    private javax.swing.JTable TVac;
    private javax.swing.JTextField TWeight;
    private javax.swing.JTable Tapoi;
    private javax.swing.JTextField Tpicture;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    // End of variables declaration//GEN-END:variables
}
